package corn

import (
	"github.com/astaxie/beego/toolbox"
	"public_security/databases"
	"public_security/models"
)

func StartCorn() {
	task1 := toolbox.NewTask("task1", "0 1 0 * * *", func() error {
		var checkSort int
		databases.DbDefault.Model(models.Process{}).Select("sort as check_sort").Where("is_check=1").Row().Scan(&checkSort)
		if checkSort > 0 {
			databases.DbDefault.Model(models.Process{}).Where("sort=?", checkSort).Update("is_check", 2)
			var nextId int
			databases.DbDefault.Model(models.Process{}).Select("id as next_id").Where("sort>? and status=2", checkSort).Order("sort").Limit(1).Row().Scan(&nextId)
			databases.DbDefault.Model(models.Process{}).Where("id=?", nextId).Update("is_check", 1)
			var maxSort int
			databases.DbDefault.Model(models.Process{}).Select("max(sort) as max_sort").Where("status=2").Row().Scan(&maxSort)
			if checkSort == maxSort {
				databases.DbDefault.Model(models.Process{}).Where("sort=1").Update("is_check", 1)
				databases.DbDefault.Model(models.Process{}).Where("sort!=1").Update("is_check", 2)
			}
		} else {
			databases.DbDefault.Model(models.Process{}).Where("sort=1").Update("is_check", 1)
			databases.DbDefault.Model(models.Process{}).Where("sort!=1").Update("is_check", 2)
		}
		return nil
	})
	toolbox.AddTask("task1", task1)
	toolbox.StartTask()
}
